<?php
namespace app\common\model;
use think\Model;

class Lottery extends Model
{
	//奖项礼品，一对多关联
	public function lotteryTerm(){
        return $this->hasMany('LotteryTerm','activity_id');
    }
	
	//规则描述
	public function getRuleDescAttr($value){
		return htmlspecialchars_decode($value);
    }
	
	/**
     * 获取活动
     * @param type $id
     * @return type
     */
	public function getActivity($uid,$shop_id,$id=0)
    {
    	$model = new self;
    	if($id){
    		$model = $model->where('id',$id);
    	}else{
    		$model = $model->where('shop_id',$shop_id);
    	}
		$model = $model->where('is_del',0);
		$model = $model->where('is_enable',1);
		$model = $model->field("id,name,tplname,num,num_upper,share_num,rule_desc");
		$model = $model->field("
			case when start_time > now() then '未开始' 
					when stop_time < now() then '已结束' 
					else '进行中' 
			end as states
		");
		$result = $model->find();	
		
		if($result){
			$result['lottery_term'] = $result -> lotteryTerm()
				->alias('LotteryTerm')
				->LeftJoin('Coupon b ','b.id= LotteryTerm.gift_id')
				->field('LotteryTerm.*')
				->field('b.name as gift_name')
				->order('LotteryTerm.sort_no','asc')
				->select();
			
			$userShareNum = model('LotteryUserShareNum')
					->where('activity_id',$result->id)
					->where('uid',$uid)
					->count();
					
			$userChanceNum = model('LotteryGetUser')
					->where('activity_id',$result->id)
					->where('uid',$uid)
					->count();	

			$result['userPrizeNum']	= $userChanceNum;		
					
			$result['chanceNum'] =  $result['num'] + $userShareNum - $userChanceNum;
		}
		
		return $result;
    }
	
	
	/**
     * 抽奖方法
     * @param type $user_id
     * @param type $new_pwd
     * @return type
     */
	private function random($prizeArr)
    {
	    $weight=0;
		$temp=array();
		foreach($prizeArr as $v){
		  	$weight+=$v['v'];
		  	for($i=0;$i<$v['v'];$i++){
		   		$temp[]=$v;//放大数组
		  	}
		}
		$int = mt_rand(0,$weight-1);//获取一个随机数
		return $temp[$int]['id'];		
    }
	
	/**
     * 开始抽奖
     * @param type $user_id
     * @param type $new_pwd
     * @return type
     */
	public function luckDraw($uid=0,$id)
    {
    	
		//中奖上限
		$userPrizeNum	= model('LotteryGetUser')
					->where('activity_id',$id)
					->where('uid',$uid)
					->group('term_id')
					->field('term_id')
					->field('count(id) as num')
					->buildSql();
		
		$gifts = model('lotteryTerm');
		$gifts = $gifts -> alias('a');
		$gifts = $gifts -> leftJoin('Coupon b','a.gift_id = b.id');
		$gifts = $gifts -> leftJoin('lottery c','a.activity_id = c.id');
		$gifts = $gifts -> leftJoin("$userPrizeNum d",'d.term_id = a.id');
		$gifts = $gifts -> where('a.activity_id',$id);
		$gifts = $gifts -> where('a.upper >ifnull(d.num,0)');
		$gifts = $gifts -> field('a.*');
		$gifts = $gifts -> field('d.num');
		$gifts = $gifts -> field('a.chance as v');
		$gifts = $gifts -> field('c.name as activity_name');
		
		//优惠券是否有效
		$gifts = $gifts->where(function ($query) {
			$query->where(function ($query) {
				$query = $query -> where('b.remain_num',">",0);
				$query = $query->where('b.is_del',0);
				$query = $query->where('b.status',1);
				$query = $query->where('b.start_time','<', date("Y-m-d H:i:s"));
				$query = $query->where('b.stop_time','>', date("Y-m-d H:i:s"));
			});
			$query->where(function($query) {
				$query->whereNotNull('b.id');
			});
		});
		
		$gifts = $gifts -> select()->toArray();
		
		$result = !count($gifts) ? 0 : $this->random($gifts);
		$prize = [];
		foreach ($gifts as $key => $value) {
			if($value['id'] == $result){ 
				$prize = $value; 
			}
		}
		
		//发放优惠券
		if($prize['gift_id'] && !model("Coupon")->grant($prize['gift_id'],$uid) ){
			return 0;	
		}	
		
		$res = model('LotteryGetUser')->save([
			'uid'=> $uid,
			'activity_id'=>$id,
			'activity_name'=>$prize['activity_name'] ?? '',
			'term_id'=> $prize['id'],
			'term_name'=> $prize['name'] ?? '',
			'nickname'=> request()->userInfo['vip_info']['name'],
			'phone'=> request()->userInfo['phone'],
			'gift_id'=> $prize['gift_id'] ?? '',
			'is_prize'=> $prize['gift_id'] ? 1 : 0
		]);
		
		return !$res ? false : $result;
    }
	
}
